// pages/confirmOrder/confirmOrder.js
import { getGoodsInfoApi } from '../../api/goods'
import { addOrderApi } from '../../api/order'
import { miniPayApi } from '../../api/common'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    noteMessage: '',
    autoSize: {
      maxHeight: 150,
      minHeight: 150
    },
    goodInfo: {},
    goodId: '',
    renderNormList: [],
    countPrice: 0,
    confirmTotalPrice: 0
  },

  noteMessageChange(e) {
    this.setData({
      noteMessage: e.detail
    })
  },

  async submitHandle() {
    const productList = this.data.confirmRenderList.map((item) => {
      // 所有的检测方法id
      let methodIds = []
      // 所有检测样品信息
      const sampleList = item.sampleNormalInfo.map((sampleNormal) => {
        // 检测样品中的所有方法id
        const methodIdList = sampleNormal.sampleNormaList.reduce((pre, cur) => {
          return [...pre, ...cur.methodVOList.map((method) => method.id)]
        }, [])
        methodIds = [...methodIds, ...methodIdList]
        return {
          sampleNum: sampleNormal.sampleNumber,
          methodIdList
        }
      })

      return {
        productId: item.goodInfo.id,
        cartId: item.cartId,
        methodIds: methodIds,
        sampleName: item.sampleName,
        sampleList
      }
    })
    console.log(productList)

    const [err, orderNum] = await addOrderApi({
      remark: this.data.noteMessage,
      productList,
      delegateVO: this.data.delegateVO
    })
    if (err) return

    const [payErr, payInfo] = await miniPayApi({ orderId: orderNum })
    if (payErr) return

    const { timeStamp = '', nonceStr = '', packAge = '', signType = '', sign = '' } = payInfo
    wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      package: packAge,
      signType: signType,
      paySign: sign,
      success(res) {
        wx.navigateTo({
          url: `/pages/paySuccess/paySuccess?orderId=${orderNum}&entryType=${
            productList[0].cartId ? 'cart' : 'goodsInfo'
          }`
        })
      },
      fail(res) {
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        })
        setTimeout(() => {
          if (productList.length > 1) {
            wx.reLaunch({
              url: '/pages/orderList/orderList?state=1'
            })
          } else {
            wx.reLaunch({
              url: `/pages/orderInfo/orderInfo?id=${orderNum}&entryType=${
                productList[0].cartId ? 'cart' : 'goodsInfo'
              }`
            })
          }
        }, 500)
      }
    })
  },

  /**
   * 获取商品详情
   */
  async getGoodsInfo() {
    const [err, info] = await getGoodsInfoApi({
      id: this.data.goodId
    })
    if (err) return
    this.setData(
      {
        goodInfo: info
      },
      () => {
        this.getNormList()
      }
    )
  },

  getNormList(methodResult, normList) {
    const renderNormList = new Map()
    for (let i = 0; i < normList.length; i++) {
      const norm = normList[i]
      const methodVOList = norm.methodVOList
      for (let j = 0; j < methodVOList.length; j++) {
        const methodVO = methodVOList[j]
        const target = methodResult.includes(`${methodVO.id}`)
        if (target) {
          const currentNorm = {
            id: norm.id,
            name: norm.testNormName
          }
          if (renderNormList.has(currentNorm.id)) {
            const normMap = renderNormList.get(currentNorm.id)
            normMap.methodVOList.push(methodVO)
            renderNormList.set(currentNorm.id, normMap)
          } else {
            renderNormList.set(currentNorm.id, { ...currentNorm, methodVOList: [methodVO] })
          }
        }
      }
    }

    return [...renderNormList.values()]
  },

  /**
   * 获取确认订单页面数据
   */
  async getConfirmData() {
    const confirmPrevData = this.data.confirmPrevData
    const confirmRenderList = []
    let confirmTotalPrice = 0
    for (let i = 0; i < confirmPrevData.length; i++) {
      const { goodId, sampleList, sampleName, totalPrice, cartId } = confirmPrevData[i]
      const [, info] = await getGoodsInfoApi({
        id: goodId
      })
      const sampleNormalInfo = sampleList.map(({ methodResult, sampleNumber }) => {
        return {
          sampleNormaList: this.getNormList(methodResult, info.normList),
          sampleNumber
        }
      })

      confirmRenderList.push({
        goodInfo: info,
        sampleNormalInfo,
        activeSample: [],
        sampleName,
        cartId
      })
      confirmTotalPrice = totalPrice + confirmTotalPrice
    }
    this.setData({
      confirmRenderList,
      confirmTotalPrice
    })
    console.log(confirmRenderList)
  },

  onChange(e) {
    const gIndex = e.currentTarget.dataset.gindex
    const detail = e.detail
    const renderKey = `confirmRenderList[${gIndex}].activeSample`
    console.log(renderKey)
    console.log(this.data[renderKey])
    this.setData({
      [renderKey]: detail
    })
  },

  /**
   * 获取商品详情
   */
  async getGoodsInfohandle() {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const confirmPrevData = wx.getStorageSync('confirmPrevData')
    const delegateVO = wx.getStorageSync('delegateVO')

    this.setData(
      {
        confirmPrevData,
        delegateVO
      },
      () => {
        this.getConfirmData()
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})
